package com.forward.utils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @Author: shafei
 * @Date: 2025/02/05 19:21
 * @description：
 **/
public class HttpServiceUtil {
    /**
     * 发送HTTP请求到指定URL，并在请求头中带上token
     *
     * @param requestUrl 请求的URL
     * @param token      请求头中的token
     * @param requestBody 请求体内容，可以为null
     * @param requestMethod 请求方法，如"GET", "POST"
     * @return 响应内容
     * @throws Exception 如果发生错误
     */
    public static String sendRequest(String requestUrl, String token, String requestBody, String requestMethod) throws Exception {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(requestMethod);
//        connection.setRequestProperty("Authorization", "Bearer " + token);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("x-access-token", token);

        if ("POST".equals(requestMethod) || "PUT".equals(requestMethod)) {
            connection.setDoOutput(true);
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }
        }

        int responseCode = connection.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new RuntimeException("Failed : HTTP error code : " + responseCode);
        }

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder response = new StringBuilder();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        return response.toString();
    }

    public static void main(String[] args) {
        try {
            String url = "http://localhost:8080/api/data";
            String token = "your_token_here";
            String requestBody = "{\"key\":\"value\"}";
            String method = "POST";

            String response = HttpServiceUtil.sendRequest(url, token, requestBody, method);
            System.out.println("Response: " + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
